;(function() {

	define(['jquery', 'angular', 'uiBootstrap', 'lazyload'], function($, angular) {

		var app = angular.module('app', ['ui.bootstrap']);

		app.factory('safeApply', ['$rootScope', function($rootScope) {//apply
		    return function(scope, fn) {
		        var phase = scope.$root.$$phase;
		        if (phase == '$apply' || phase == '$digest') {
		            if (fn && ( typeof (fn) === 'function')) fn();
		        } else {
		            scope.$apply(fn);
		        }
		    }
		}])
		.filter('tohtml', ['$sce', function($sce) {
		    return function(val) {
		        return $sce.trustAsHtml(val);
		    };
		}]);
		app.controller('storeLists', ['$scope', '$http', '$timeout', 'safeApply', function($scope, $http, $timeout, safeApply) {

			var currentC = $('.right .classify').attr('data');//当前选择的大类小类
			var hits = 16;//分页每页显示数量

			$scope.maxSize = 5;
			$scope.pageNum = 10;//总页数,10页==100,每个都要*10
			$scope.currentPage = 1;//当前页数
			$scope.clientid = $('.c-header').attr('init');//商户id
			$scope.productList = [];//列表数据
			$scope.lsearch = {//左边搜索
				big: '',//input字段
				p1: '',//最低价
				p2: ''//最高价
			}

			$scope.classify = {
				bigCates: '',
				smallCates: '',
				brands: '',
				attrs: '',
				inputContent: '',
				filter1: '',//不带价格
				filter2: '',//带价格最终
				sort: '',
				order: '-',//升序还是降序
				p1: '',//最低价,
				p2: ''//最高价
			}

			var classify = $scope.classify;

			$scope.searchBtn = function() {

				var text = $('.search .search-bar input').val();

				if(text != '') {

					classify = {
						bigCates: '',
						smallCates: '',
						brands: '',
						attrs: '',
						inputContent: text,
						filter1: '',//不带价格
						filter2: '',//带价格最终
						sort: '',
						order: '-',//升序还是降序
						p1: '',//最低价,
						p2: ''//最高价
					}

					setList(0);
					$('html, body').animate({scrollTop: 580}, 300);
				}
			}

			$scope.setList = function(start) {//价格选项

				classify.inputContent = $('.options input.search-name').val();

				var prefix = classify.filter1 == '' ? '' : ' AND ';
				var filters = '';
				if(classify.p1 && classify.p2)
					filters = prefix + 'shop_price>'+ (parseFloat(classify.p1)-1) +' AND shop_price<'+ (parseFloat(classify.p2)+1);

				else if(classify.p1)
					filters = prefix + 'shop_price>'+ (parseFloat(classify.p1)-1);
				else if(classify.p2)
					filters= prefix + 'shop_price<'+ (parseFloat(classify.p2)+1);

				classify.filter2 = classify.filter1 + filters;
				setList(start);
			}

			function setList(start) {//拼接json,查询数据

				var json = '{\
					\"start\": '+ start +',\
					\"hits\": '+ hits +',\
					\"clientID\": \"'+ $scope.clientid +'\",\
					\"bigCates\": \"'+ classify.bigCates +'\",\
					\"smallCates\": \"'+ classify.smallCates +'\",\
					\"fields\": \"name,shop_price,thumb,thumb1,thumb2,thumb3,thumb4,thumb5,saleqty,id\",\
					\"brands\": \"'+ classify.brands +'\",\
					\"attrs\": \"'+ classify.attrs +'\",\
					\"inputContent\": \"'+ classify.inputContent +'\",\
					\"filters\": \"is_on_sale=\\"Y\\"'+ (classify.filter2 == '' ? 
						(classify.filter1 == '' ? '' : ' AND '+ classify.filter1) : 
						(' AND '+ classify.filter2)) +'\",\
					\"sort\": \"'+ classify.sort +'\"\
				}';

				getGoodsList($http, json, function(res) {

					if(res.data.code == 0) {
						
						if(res.data.message.result.items && res.data.message.result.items.length > 0) {
							$scope.productList = res.data.message.result.items;
							$scope.pageNum = Math.ceil(res.data.message.result.total/hits)*10;

							$timeout(function() {

								$('img.lazy').lazyload();
							}, 10);
						} else {
							$scope.pageNum = 0;
							$scope.productList = [];
							$scope.currentPage = 1;
						}
					}
				});

				safeApply($scope);
			}

			$scope.pageChanged = function() {

				var start = ($scope.currentPage - 1) * hits;
				setList(start);
			}

			$scope.optionSelect = function(opt, sort) {//升降筛选
				$scope.currentPage = 1;

				switch(opt) {

					case 'all':
						classify.sort = '';
						break;//case all

					case 'qty':
						classify.sort = 'saleqty'+ sort;
						break;//case qty

					case 'price':
						classify.sort = 'shop_price'+ sort;
						break;//case price

					case 'saletime':
						classify.sort = 'saletime'+ sort;
						break;//case time
				}
				setList(0);
			}

			$scope.classSel = function(cla, text) {

				var filters = '';

				if(cla == 'other')
					filters = text + '=\\"Y\\"';

				if(text == 'all') {
					text = '';
					filters = '';
				}

				classify.inputContent = '';
				classify.p1 = '';
				classify.p2 = '';
				classify.filter1 = filters;
				classify.filter2 = '';
				classify[cla] = text;
				classify.sort = '';

				$('.inner .right .options li').eq(0).addClass('active').removeClass('up')
				.siblings('li').removeClass('active up');

				setList(0);
			}

			setList(0);
			//初始化数据,存在大小类选择则去拉取大小类数据否则则拉取默认数据
		}])
		.directive('optBtn', function() {
			return {

				restrcit: 'A',
				scope: true,
				link: function(scope, el, attrs) {

					scope.state = false//状态,false表降序,true表升序
					var item = attrs.item;
					var pScope = scope.$parent;

					el.on('click', function() {
						scope.state = !scope.state;

						if(el.hasClass('active') && item == 'all') {

							el.toggleClass('up', scope.state);
							return false;
						}
							
						el.addClass('active');
						$(el).siblings('li').removeClass('active');
						
						el.toggleClass('up', scope.state);
						pScope.optionSelect(item, scope.state?'+':'-');

						pScope.classify.order = scope.state?'+':'-';
					});
				}
			}
		})
		.directive('classify', function() {
			return {

				restrcit: 'A',
				scope: true,
				link: function(scope, el, attrs) {

					var cla = attrs.classify;
					var text = attrs.text;

					el.on('click', function() {

						scope.$parent.classSel(cla, text);
					});
				}
			}
		});

		angular.element(document).ready(function() {
			angular.bootstrap(document, ['app']);
		});
		
		return app;
	});

	function getUrlOpt(name){

	     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	     var r = window.location.search.substr(1).match(reg);

	     if(r != null) 
	     	return  unescape(r[2]); 
	     return null;
	}

	function getGoodsList($http, json, fn) {
		
		$http({
			method: 'POST',
			url: '/control/pub/command',
			params: {
				'command': "com.jackrain.ds.CommESGoodsCloudSearchpub",
				'getjson': true,
				'JSON': json
			}
		}).then(function(res) {
			
			fn(res);
		});
	}
})();